package com.cwx.mychat.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.IOException;

@Slf4j
@Configuration
public class RedisConfig<V> {

    @Bean
    public RedisTemplate<String, V> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, V> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        //设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.port}")
    private Integer redisPort;

    @Value("${spring.data.redis.password}")
    private String password;


    @Bean(name = "redissionClient", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try{
            //获取当前核心数
            int cores = Runtime.getRuntime().availableProcessors();
            log.info("--------开始加载Redisson配置--------");
            Config config = new Config();
            config.useSingleServer()
                    .setAddress("redis://" + redisHost + ":" + redisPort) //单机模式
                    .setPingConnectionInterval(10000); //心跳检测间隔
            config.useSingleServer()
                    .setPassword(password)
                    .setConnectionPoolSize(64) //连接池最大连接数
                    .setConnectionMinimumIdleSize(1) //最小空闲连接
                    .setIdleConnectionTimeout(30000) //空闲连接超时时间
                    .setConnectTimeout(10000) //连接超时时间
                    .setTimeout(3000) //命令执行超时时间
                    .setRetryAttempts(5) //重试次数
                    .setRetryInterval(1500); //重试间隔时间
            //使用json序列化
            Codec code = new JsonJacksonCodec();
            config.setCodec(code);
            return Redisson.create(config);
        }catch (Exception e){
            log.error("redisson配置错误", e);
            return null;
        }

    }
}
